package Utils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;


/**
 * bean与map互相转化工具
 *
 * @author dbw
 */
public class Bean2MapUtil {
    public static Map<String, String> Object2MapType(Class clazz) throws IllegalAccessException, InstantiationException {

        Map<String, String> map = new HashMap<String, String>();
        Object obj = null;

        // 使用newInstance来创建对象
        obj = clazz.newInstance();
        // 获取类中的所有字段
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {

            map.put(field.getName(), field.getType().getName());
        }

        return map;
    }

    public static Map<String, Object> objectToMap(Object bean) {
        Map<String, Object> returnMap = null;
        if (bean == null)
            return null;
        try {
            Class type = bean.getClass();
            returnMap = new HashMap<String, Object>();
            BeanInfo beanInfo = Introspector.getBeanInfo(type);
            PropertyDescriptor[] propertyDescriptors = beanInfo
                    .getPropertyDescriptors();
            for (int i = 0; i < propertyDescriptors.length; i++) {
                PropertyDescriptor descriptor = propertyDescriptors[i];
                String propertyName = descriptor.getName();
                if (!propertyName.equals("class")) {
                    Method readMethod = descriptor.getReadMethod();
                    Object result = readMethod.invoke(bean, new Object[0]);
                    if (result != null&&result.toString().length()>0) {
                        returnMap.put(CommUtil.camelToUnderline(propertyName),
                                result);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnMap;
    }
}
